<?php
namespace frontend\controllers;

use Yii;
use frontend\models\PostForm;
use common\models\CatModel;
use common\models\PostExtendModel;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * 基类控制器
 */
class PostController extends BaseController
{

    public function actions()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'create','upload','ueditor'],
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['create','upload','ueditor'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*' => ['get','post'],
                ],
            ],
            'upload'=>[
                'class' => 'common\widgets\file_upload\UploadAction',
                'config' => [
                    'imagePathFormat' => "/image/{yyyy}{mm}{dd}/{time}{rand:6}",
                ]
            ],
            'ueditor'=>[
                'class' => 'common\widgets\ueditor\UeditorAction',
                'config'=>[
                    //上传图片配置
                    'imageUrlPrefix' => "", /* 图片访问路径前缀 */
                    'imagePathFormat' => "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }   

    // 创建文章
    public function actionCreate()
    {
        $model = new PostForm();
        $model->setScenario(PostForm::SCENARIOS_CREATE);
        if($model->load(Yii::$app->request->post())&& $model->validate()){
            if(!$model->create()){
                Yii::$app->session->setFlash('warning',$model->_lastError);
            }else{
                return $this->redirect(['post/view','id' => $model->id]);
            }
        }
        $cat = CatModel::getAllCats();
        return $this->render('create',[
            'model' => $model,
            'cat' => $cat
        ]);
    }

    // 查看文章
    public function actionView()
    {
        $model = new PostForm();
        $id = Yii::$app->request->get('id');
        $data = $model->getViewById($id);

        $model = new PostExtendModel();
        $model->upCounter(['post_id' => $id],'browser',1);

        return $this->render('view',[
            'data' => $data
        ]);
    }

}